<?php

namespace App\Models\Common;

use App\Models\BaseModel;
use App\Helpers\Code;

class Department extends BaseModel
{

    protected $table = 'departments';
    protected $fillable = ['title', 'description', 'data_scope'];
    public $params = ['title'];
    public $sorters = ['title', 'created_at'];

    public function users()
    {
        return $this->hasMany('App\Models\Account\User', 'department_id');
    }

    public function addDepartment($data)
    {
        $data['data_scope'] = $this->getDataScope();
        return $this->create($data);
    }

    public function deleteDepartment($id)
    {
        $model = $this->with('users')->find($id);

        if (!$model) {
            return null;
        } else if ($model->users->count() > 0) {
            return Code::INSIDE_EXIST_DEPENDENCE;
        }

        return $model->delete();
    }

    public function editDepartment($id, $data)
    {
        $model = $this->find($id);

        if (!$model) {
            return null;
        }

        return $model->updateOrCreate(['id' => $id], $data);
    }

    public function getDepartmentList($limit, $sorter, $search)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        $model = $this->orderBy($sorter[0], $sorter[1]);
        $model->select(['id', 'title', 'description', 'created_at']);

        foreach ($search as $key => $value) {
            switch ($key) {
                case 'title':
                    $model->where($key, 'like', '%' . $value . '%');
                    break;
            }
        }

        return $model->paginate($perPage)->toArray();
    }

    public function getDepartmentListAll()
    {
        return $this->all(['id', 'title'])->toArray();
    }

    public function getDepartmentUserList($id)
    {
        $model = $this->find($id);

        if (!$model) {
            return null;
        }

        return $model->users()->get(['id', 'username'])->toArray();
    }

    public function getDepartment($id)
    {
        $model = $this->find($id);

        if (!$model) {
            return null;
        }

        return $model->toArray();
    }

}
